import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Input, 
  Space, 
  Modal, 
  Form, 
  Switch, 
  Typography, 
  message,
  Card,
  Tag,
  Popconfirm,
  Row,
  Col,
  List
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  SearchOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { rulesApi } from '../api';
import { Rule, Condition } from '../types';
import './RulesManager.css';

const { Title, Text } = Typography;
const { Search } = Input;

const RulesManager: React.FC = () => {
  const [rules, setRules] = useState<Rule[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRule, setEditingRule] = useState<{ index: number; rule: Rule } | null>(null);
  const [form] = Form.useForm();
  const [viewConditions, setViewConditions] = useState<{ruleName: string, conditions: Condition[]} | null>(null);

  // 加载规则数据
  const loadRules = async () => {
    setLoading(true);
    try {
      const data = await rulesApi.getRules();
      setRules(data);
    } catch (error) {
      message.error('加载规则失败');
    } finally {
      setLoading(false);
    }
  };

  // 搜索规则
  const handleSearch = async (value: string) => {
    setLoading(true);
    try {
      const data = await rulesApi.searchRules(value);
      setRules(data);
    } catch (error) {
      message.error('搜索失败');
    } finally {
      setLoading(false);
    }
  };

  // 刷新数据
  const handleRefresh = () => {
    loadRules();
  };

  // 创建新规则
  const handleCreate = () => {
    setEditingRule(null);
    form.resetFields();
    form.setFieldsValue({
      'rules-name': '',
      activate: true,
      conditions: [{ content: '', value: true }]
    });
    setModalVisible(true);
  };

  // 编辑规则
  const handleEdit = (index: number, rule: Rule) => {
    setEditingRule({ index, rule });
    form.setFieldsValue(rule);
    setModalVisible(true);
  };

  // 删除规则
  const handleDelete = async (index: number) => {
    try {
      await rulesApi.deleteRule(index);
      message.success('删除成功');
      loadRules();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 保存规则
  const handleSave = async (values: any) => {
    try {
      if (editingRule) {
        // 更新现有规则
        await rulesApi.updateRule(editingRule.index, values);
        message.success('更新成功');
      } else {
        // 创建新规则
        await rulesApi.createRule(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      loadRules();
    } catch (error) {
      message.error(editingRule ? '更新失败' : '创建失败');
    }
  };

  useEffect(() => {
    loadRules();
  }, []);

  // 表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (index: number) => <Text code>{index}</Text>
    },
    {
      title: '规则名称',
      dataIndex: 'rules-name',
      key: 'rules-name',
      width: 150,
      render: (name: string) => <Text strong>{name}</Text>
    },
    {
      title: '激活',
      dataIndex: 'activate',
      key: 'activate',
      width: 80,
      render: (activate: boolean) => (
        <Switch checked={activate} checkedChildren="启用" unCheckedChildren="禁用" disabled />
      )
    },
    {
      title: '条件数量',
      key: 'conditionCount',
      width: 100,
      render: (_: any, record: any) => (
        <Tag color="blue">{record.conditions.length} 个条件</Tag>
      )
    },
    {
      title: '条件详情',
      key: 'conditions',
      render: (_: any, record: any) => {
        const preview = record.conditions.slice(0, 2);
        const more = record.conditions.length > 2;
        return (
          <Space direction="vertical" size="small" style={{ width: '100%' }}>
            {preview.map((condition: Condition, idx: number) => (
              <div key={idx} style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <Text style={{ flex: 1, fontSize: '12px' }}>{condition.content}</Text>
                <Switch
                  size="small"
                  checked={condition.value}
                  disabled
                  checkedChildren="启用"
                  unCheckedChildren="禁用"
                />
              </div>
            ))}
            {more && (
              <Button type="link" size="small" onClick={() => setViewConditions({ruleName: record['rules-name'], conditions: record.conditions})}>
                查看全部（共{record.conditions.length}条）
              </Button>
            )}
          </Space>
        );
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: any) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record.index, record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个规则吗？"
            onConfirm={() => handleDelete(record.index)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              danger
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 转换数据格式用于表格显示
  const tableData = rules.map((rule, index) => ({ ...rule, index }));

  return (
    <div className="rules-manager">
      <Card className="header-card">
        <Row align="middle" justify="space-between">
          <Col>
            <Title level={2} style={{ margin: 0, color: '#1890ff' }}>
              🚗 DCarPai UBBC 规则管理
            </Title>
            <Text type="secondary">管理和维护UBBC内容规则</Text>
          </Col>
          <Col>
            <Space>
              <Search
                placeholder="搜索规则名称或内容..."
                allowClear
                enterButton={<SearchOutlined />}
                size="large"
                onSearch={handleSearch}
                style={{ width: 300 }}
              />
              <Button
                icon={<ReloadOutlined />}
                onClick={handleRefresh}
                size="large"
              >
                刷新
              </Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleCreate}
                size="large"
              >
                新建规则
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      <Card className="table-card">
        <Table
          columns={columns}
          dataSource={tableData}
          rowKey="index"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条规则`,
            pageSizeOptions: ['10', '20', '50'],
          }}
          size="middle"
        />
      </Card>
      {/* 条件详情弹窗 */}
      <Modal
        open={!!viewConditions}
        title={viewConditions ? `${viewConditions.ruleName} - 条件列表（共${viewConditions.conditions.length}条）` : ''}
        onCancel={() => setViewConditions(null)}
        footer={null}
        width={480}
      >
        <List
          dataSource={viewConditions ? viewConditions.conditions : []}
          renderItem={(item, idx) => (
            <List.Item>
              <Text style={{ fontSize: 14 }}>{idx + 1}. {item.content}</Text>
              <Switch
                size="small"
                checked={item.value}
                disabled
                checkedChildren="启用"
                unCheckedChildren="禁用"
              />
            </List.Item>
          )}
        />
      </Modal>

      <Modal
        title={editingRule ? '编辑规则' : '新建规则'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={form.submit}
        width={Math.max(800, Math.floor(window.innerWidth * 0.6))}
        okText="保存"
        cancelText="取消"
        footer={[
          <Button
            key="add"
            type="dashed"
            onClick={() => {
              // 直接调用 form 的 add 方法
              const conditions = form.getFieldValue('conditions') || [];
              form.setFieldsValue({ conditions: [...conditions, { content: '', value: true }] });
            }}
            icon={<PlusOutlined />}
            style={{ marginLeft: 8 }}
          >
            添加条件
          </Button>,
          <Button key="cancel" onClick={() => setModalVisible(false)}>
            取消
          </Button>,          
          <Button key="ok" type="primary" onClick={form.submit}>
            保存
          </Button>
        ]}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Form.Item
            label="规则名称"
            name="rules-name"
            rules={[{ required: true, message: '请输入规则名称' }]}
          >
            <Input placeholder="输入规则名称" />
          </Form.Item>
          <Form.Item
            label="激活状态"
            name="activate"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>
          <Form.List name="conditions">
            {(fields, { remove }) => (
              <div style={{ maxHeight: 260, overflowY: 'auto', border: '1px solid #f0f0f0', borderRadius: 8, padding: 4, background: '#fafbfc', marginBottom: 12 }}>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: 4 }}>
                  <Text strong style={{ fontSize: 13 }}>条件列表</Text>
                </div>
                {fields.map(({ key, name, ...restField }) => (
                  <div key={key} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, padding: '2px 0' }}>
                    <span style={{ minWidth: 60, fontSize: 12, color: '#888' }}>* 条件内容</span>
                    <Form.Item
                      {...restField}
                      name={[name, 'content']}
                      rules={[{ required: true, message: '请输入条件内容' }]}
                      style={{ flex: 1, marginBottom: 0 }}
                    >
                      <Input placeholder="输入条件内容" />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, 'value']}
                      valuePropName="checked"
                      style={{ marginBottom: 0, marginLeft: 8 }}
                    >
                      <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                    </Form.Item>
                    <Button
                      type="link"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => remove(name)}
                      style={{ marginLeft: 4 }}
                    >
                      删除
                    </Button>
                  </div>
                ))}
              </div>
            )}
          </Form.List>
        </Form>
      </Modal>
    </div>
  );
};

export default RulesManager;
